package com.design.fitment.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.design.fitment.R;
import com.design.fitment.adapter.CasesListAdapter;
import com.design.fitment.entity.SheJiBen;
import com.design.fitment.util.DesignNetworkUtil;
import com.design.fitment.util.RequestDataCallback;
import com.design.fitment.view.MainHeaderView;
import com.design.fitment.view.XListView;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;


public class MainFragment extends Fragment {
    @ViewInject(R.id.lv_main)
    private XListView mlist;
    private MainHeaderView headerView;
    private CasesListAdapter mCasesAdapter = null;
    private List<SheJiBen.DataEntity.CasesEntity> mCases = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, null);
        ViewUtils.inject(this, view);
        initViews();
        loadBanner();
        return view;
    }

    private void initViews() {
        headerView = new MainHeaderView(getActivity());
        mlist.addHeaderView(headerView);
        mCasesAdapter = new CasesListAdapter(getActivity(),mCases);
        mlist.setAdapter(mCasesAdapter);
        mlist.setPullRefreshEnable(true);
        mlist.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                loadBanner();
                if (mCases != null) {
                    mlist.stopRefresh();
                }
            }

            @Override
            public void onLoadMore() {

            }
        });



    }

    private void loadBanner() {
        DesignNetworkUtil.getInstance().getBannaer(new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                Gson gson = new Gson();
                SheJiBen banner = gson.fromJson(response, SheJiBen.class);
                if (banner != null) {

                    mCases.addAll(banner.getData().getCases());

                }
                mCasesAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException error) {
                Log.d("onFailure", "onFailure() returned: " + "error");
            }
        });
        headerView.loadBanner();

    }


}